/******
 * 1.引入axios
2.创建axios实例  用axios.create
3.设置baseUrl 和timeOut
4.写请求拦截
5.写响应拦截
6.导出
 */

import axios from 'axios';
import { Message } from 'element-ui';
export const instance = axios.create({
    baseURL: '/api',
    timeout: 10000
})



//设置请求拦截
instance.interceptors.request.use(
    (config) => {
        config.headers['Content-Type'] = 'application/json'
        let token = window.sessionStorage.getItem("token") ? window.sessionStorage.getItem("token") : ""
        if (token != "") {
            config.headers['token'] = token
        }
        return config
    },
    (err) => {
        Promise.reject(err)
    }
)
//设置响应拦截
instance.interceptors.response.use(   //响应拦截
    (res) => {
        const contentType = res.headers['content-type']
        if (contentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8") {
            let blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            let url = window.URL.createObjectURL(blob);
            const link = document.createElement('a'); // 创建a标签
            link.href = url;
            link.click();
            URL.revokeObjectURL(url); // 释放内存
            return
        }
        if (res.data.code != 200) {
            Message.error(res.data.msg)
        }
        return res
    },
    (err) => {
        Message.error(err.message)
        return Promise.reject(err)
    }
)

//封装get和post请求
export async function http (url = '', data = {}, type = 'POST') {
    type = type.toUpperCase()
    if (type == 'GET') {
        const res = await instance.get(url, { params: data })
        return new Promise((resolve, reject) => {
            if (res.status == 200) {
                resolve(res)
            } else {
                reject(res)
            }
        })
    } else if (type == 'POST') {
        const res = await instance.post(url, data)
        return new Promise((resolve, reject) => {
            if (res.status == 200) {
                resolve(res)
            } else {
                reject(res)
            }
        })
    }
}
